/**
 * Copyright(c)2012 Beijing PeaceMap Co.,Ltd.
 * All right reserved. 
 */
package com.pmc.dwa.security.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pmc.dwa.common.utils.Escape;
import com.pmc.dwa.common.utils.JsonGrid;
import com.pmc.dwa.common.utils.PaginationSupport;
import com.pmc.dwa.security.model.TGroup;
import com.pmc.dwa.security.model.TSect;
import com.pmc.dwa.security.model.TSection;
import com.pmc.dwa.security.service.ISectionResourceService;

/**
 * @description 单位/资源管理
 * @author aokunsang
 * @date 2013-1-8
 */
@Controller
@RequestMapping("/rbac")
public class SectionResourceController {

	@Autowired
	private ISectionResourceService srService;
	
/*--------------------------单位管理-------------------------------------------------*/
	/* 分页取得单位信息*/
	@RequestMapping(value="getAllSection",method={RequestMethod.POST,RequestMethod.GET})
	public @ResponseBody JsonGrid<TSection> getAllSection(
			@RequestParam(required=true) Integer page,
			@RequestParam(required=true) Integer rows,
			String sectionname){
		PaginationSupport<TSection> pager = srService.getPagesTSection(sectionname, page, rows);
		return new JsonGrid<TSection>(pager);
	}
	
	/* 下拉列表展示单位信息*/
	@RequestMapping(value="getSectionList",method={RequestMethod.GET})
	public @ResponseBody List<TSection> getSectionList(){
		List<TSection> tSections = srService.getAllSection();
		if(tSections==null){
			tSections = new ArrayList<TSection>();
		}
		return tSections;
	}
	
	@RequestMapping(value="getSection/{sectionid}")
	public @ResponseBody TSection getSection(@PathVariable String sectionid){
		return srService.getSectionByid(sectionid);
	}
	
	@RequestMapping(value="addSection",method={RequestMethod.POST})
	public @ResponseBody String addSection(TSection section){
		try {
			section.setId(UUID.randomUUID().toString());
			section.setCreateTime(new Timestamp(System.currentTimeMillis()));
			section.setStatus((byte)1);
			srService.addSection(section);
			return "{success:true,msg:''}";
		} catch (Exception e) {
			return "{success:false,msg:'"+Escape.escape(e.getMessage())+"'}";
		}
	}
	
	@RequestMapping(value="editSection/{sectionid}",method={RequestMethod.POST})
	public @ResponseBody String editSection(@PathVariable String sectionid,TSection section){
		try {
			section.setId(sectionid);
			section.setCreateTime(new Timestamp(System.currentTimeMillis()));
			srService.editSection(section);
			return "{success:true,msg:''}";
		} catch (Exception e) {
			return "{success:false,msg:'"+Escape.escape(e.getMessage())+"'}";
		}
	}
	
	@RequestMapping(value="setSectionStatus",method={RequestMethod.POST})
	public @ResponseBody String setSectionStatus(String sectionid,String statVal){
		if(StringUtils.isEmpty(sectionid)){
			return "{success:0,msg:'"+Escape.escape("提供资料不全，无法更新用户状态。")+"'}";
		}
		if(statVal==null || (!"0".equals(statVal) && !"1".equals(statVal))){
			return "{success:0,msg:'"+Escape.escape("错误的状态值")+"'}";
		}
		try {
			srService.editSectionColumnVal(sectionid, "STATUS", statVal);
			return "{success:1}";
		} catch (Exception e) {
			return "{success:0,msg:'"+e.getMessage()+"'}";
		}
	}
	/**
	 * 删除区划
	 * @param sectionid
	 * @return
	 */
	@RequestMapping(value="delSection/{sectionid}",method=RequestMethod.POST)
	public @ResponseBody String delUser(@PathVariable String sectionid){
		try {
			srService.delSection(sectionid);
			return "{success:true,msg:'删除成功!'}";
		} catch (Exception e) {
			e.printStackTrace();
			return "{success:false,msg:'请先删除该与该科室相关联的用户。'}";
		}
	}
/*----------------------------资源管理------------------------------------------------------*/
	@RequestMapping(value="getAllSect",method=RequestMethod.POST)
	public @ResponseBody JsonGrid<TSect> getAllSect(
			///@RequestParam(required=true) Integer page,
			//@RequestParam(required=true) Integer rows,
			String sectname){
		//PaginationSupport<TSect> pager = srService.getPagesTSect(sectname, page, rows);
		List<TGroup> groupList = srService.getAllGroup();
		Map<String,TGroup> map = new HashMap<String, TGroup>();
		for(int i=0,length=groupList.size();i<length;i++){
			TGroup group = groupList.get(i);
			map.put(group.getId(), group);
		}
		List<TSect> list = srService.getAllTsect(sectname);
		Set<String> strSet = new HashSet<String>();
		if(list!=null){
			for(TSect sect : list){
				if("0".equals(sect.getPid())){
					sect.set_parentId(sect.getGroup_id());
					strSet.add(sect.getGroup_id());
				}
			}
			for(String str : strSet){
				list.add(new TSect(str, map.get(str).getTitle()));
			}
		}else{
			list = new ArrayList<TSect>();
		}
		return new JsonGrid<TSect>(list.size()+strSet.size(),list);
	}
	
	@RequestMapping(value="getSect/{sectid}")
	public @ResponseBody TSect getSect(@PathVariable String sectid){
		return srService.getSect(sectid);
	}
	
	@RequestMapping(value="addSect",method={RequestMethod.POST})
	public @ResponseBody String addSect(TSect sect){
		try {
			sect.setId(UUID.randomUUID().toString());
			sect.setUpdatetime(new Timestamp(System.currentTimeMillis()));
			sect.setStatus(Short.valueOf("1"));sect.setVersion((long)1.0);
			srService.addSect(sect);
			return "{success:true,msg:''}";
		} catch (Exception e) {
			return "{success:false,msg:'"+Escape.escape(e.getMessage())+"'}";
		}
	}
	
	@RequestMapping(value="editSect/{secid}",method={RequestMethod.POST})
	public @ResponseBody String editSect(@PathVariable String secid,TSect sect){
		try {
			sect.setId(secid);
			sect.setUpdatetime(new Timestamp(System.currentTimeMillis()));
			srService.editSect(sect);
			return "{success:true,msg:''}";
		} catch (Exception e) {
			return "{success:false,msg:'"+Escape.escape(e.getMessage())+"'}";
		}
	}
	
	@RequestMapping(value="delSect/{sectid}",method=RequestMethod.POST)
	public @ResponseBody String delSect(@PathVariable String sectid){
		try {
			srService.delSect(sectid);
			return "ok";
		} catch (Exception e) {
			e.printStackTrace();
			return "fail";
		}
	}
	
	@RequestMapping(value="getAllGroup",method={RequestMethod.GET})
	public @ResponseBody List<TGroup> getAllGroup(){
		List<TGroup> groupList =  srService.getAllGroup();
		return groupList;
	}
	
	@RequestMapping(value="getParentSect/{groupid}/{slevel}",method={RequestMethod.GET,RequestMethod.POST})
	public @ResponseBody List<Map<String,String>> getParentSectByGroupid(
															@PathVariable String groupid,
															@PathVariable Integer slevel){
		List<Map<String,String>> resultList = new ArrayList<Map<String, String>>();
		Map<String,String> resultMap = null;
		if(slevel <= 1){  //无等级、应用级
			resultMap = new HashMap<String, String>();
			resultMap.put("id", "0");resultMap.put("comments", "无需分组");
			resultList.add(resultMap);
		}else{
			List<TSect> sectList = srService.findParentSect(groupid,slevel-1);
			Map<String,String> paretnSecMap = new HashMap<String,String>();
			if(slevel > 2){ //资源等级为操作级
				List<TSect> _list = srService.findParentSect(groupid,slevel-2);
				for(TSect sect : _list){
					paretnSecMap.put(sect.getId(), sect.getComments());
				}
			}
			for(TSect sect : sectList){
				resultMap = new HashMap<String, String>();
				resultMap.put("id", sect.getId());resultMap.put("comments", sect.getComments());
				if(slevel > 2){
					resultMap.put("group", paretnSecMap.get(sect.getPid()));
				}
				resultList.add(resultMap);
			}
		}
		return resultList;
	}
}
